/**
 * js 工具类
 */


define(['jquery','init','buttonEvent','uploadfiles','bsMsgServ'],function($,init,buttonEvent,uploadfiles,bsMsgServ){
	
	'use strict';
	
	//获取附件列表url
	var uploadListurl = '/upload/query/getInitListDomain.action'
	
	//附件预览html
	var _archivePreviewHtml = '<div class="col-md-2 border-label">'+
								'<label class="control-label">附件</label>'+
							  '</div>'+
							  '<div class="col-md-10 ">'+
								'<div id="archive" name="archive"></div>'+
							  '</div>';
	//附件上传删除html
	var _archiveUploadHtml = '<div class="col-md-2 border-label"></div>'+
				'<div class="col-md-10">'+
				'<input id="file_upload" name="file_upload" type="file" multiple="true">'+
				'<div id="queue"></div>'+
				'</div>'+
				_archivePreviewHtml;
				
	var public_method = {
		/**
		 * 检查可执行的操作状态
		 * @param _options.records	数据集合
		 * @param _options.status   审核状态标志
		 */
		checkStatus:function(_options){
			var retVal = false,ids
			//参数判断
			if(_options && _options.records ){
				
				for(var i=0;i<_options.records.length;i++){
					var el = _options.records[i];
					
					if(el.id){
						ids=!ids?el.id:ids+','+el.id	
					}
					
					//生成id字符串	
					retVal = ids
					
					//未执行审核操作
					if(!el.status){
						continue;	
					}
					
					//判断是否存在已审核通过的数据							
					if(el.status && el.status==1){
						
						retVal = false;
						break;
					}							
					
				}						
										
			}
			
			return retVal;
			
		},
		
		
		/**
		 * 获取未读信息
		 * @param _options.typeid
		 */
		getNewDoc:function(_options){		
			var _df = private_method.getNotifyid();
			var _default = $.extend({},_df,_options);
			var ret 
			var _param = {
				url:'/'+init.getSite()+'/document/query/getNew.action',
				data:{typeid:_default.typeid},				
				async:false,
				success:function(data){
					ret = data						
				}
				,
				failure:function(){
					bsMsgServ.errorSlide(codeDef.getConfig({type:'load',code:'error'}))
				}
				
			}
			
			$.ajax(_param)
			return ret
		}
		,
		/**
		 * 获取未读信息数量
		 */
		getNewCount:function(_options){
			var _df = private_method.getNotifyid();
			var _default = $.extend({},_df,_options);
			var ret 
			var _param = {
				url:'/'+init.getSite()+'/document/query/getNew.action',
				data:{typeid:_default.typeid},				
				async:false,
				success:function(data){
					ret = data						
				}
				,
				failure:function(){
					bsMsgServ.errorSlide(codeDef.getConfig({type:'load',code:'error'}))
				}
				
			}
			
			$.ajax(_param)
			return ret
		}
		,
		/**
		 * 获取待处理工作
		 */
		getIssueCount:function(_options){
			var ret 
			var _param = {
				url:'/'+init.getSite()+'/workFlow/query/flowOperateCount.action',								
				async:false,
				success:function(data){
					ret = data						
				}
				,
				failure:function(){
					bsMsgServ.errorSlide(codeDef.getConfig({type:'load',code:'error'}))
				}
				
			}
			
			$.ajax(_param)
			return ret
			
		}
		,
		
		/**
		 * 获取待处理工作
		 */
		getIssueListCount:function(_options){
			var ret 
			var _param = {
				url:'/'+init.getSite()+'/workFlow/query/flowOperateCount.action',								
				async:false,
				success:function(data){
					ret = data						
				}
				,
				failure:function(){
					bsMsgServ.errorSlide(codeDef.getConfig({type:'load',code:'error'}))
				}
				
			}
			
			$.ajax(_param)
			return ret
			
		}
		,
			
		/**
		 * 更新文档提示数字
		 */
		updateDocBadge:function(){
			
			//update doc notify
			var data = public_method.getNewCount();
			var cnt = '';
			if(data && data.length){
				cnt = data.length;
			}
			var _el = $('.badge-doc-notify')
			if(_el.length>0){
				_el.html(cnt);
			}
		}
		,
		/**
		 * 获取事项提示信息
		 */
		updateIssueBadge:function(){
			//update issue notify
			var data = public_method.getIssueCount();
			var cnt = 0;
			
			if(data && data.length){
				$.each(data,function(i,o){
					cnt += parseInt(o.bizCount);
					
					//查找业务badge
					var _class = '.badge-'+o.bizcode + '-notify'
					var _badgeEl = $(_class)
					if(_badgeEl.length>0){
						_badgeEl.html(o.bizCount);
					}
				})				
			}
			var _el = $('.badge-issue-notify')
			if(_el.length>0){
				_el.html(cnt);
			}
			
		}
		,
		/**
		 * 获取未读邮件信息
		 */
		updateMailBadge:function(){
			
			var _param = {
				url:'/'+init.getSite()+'/mailInfo/query/getBadge.action',								
				async:false,
				success:function(data){					
					if(data){
						var _badgeEl = $('.badge-mail-notify')
						if(_badgeEl.length>0){
							if(data.recived){
								_badgeEl.html(data.recived);									
							}else{
								_badgeEl.html('');	
							}
						}
					}
				}
				,
				failure:function(){
					bsMsgServ.errorSlide(codeDef.getConfig({type:'load',code:'error'}))
				}
				
			}
			
			$.ajax(_param)
		}
		,
		/**
		 * 获取事项提示信息
		 */
		updateIssueListBadge:function(){
			//update issue notify
			var data = public_method.getIssueListCount();
			var cnt = 0;
			
			if(data && data.length){
				$.each(data,function(i,o){
					cnt += parseInt(o.bizCount);
					
					//查找业务badge
					var _class = '.badge-'+o.bizcode + '-notify'
					var _badgeEl = $(_class)
					if(_badgeEl.length>0){
						_badgeEl.html(o.bizCount);
					}
				})				
			}
			var _el = $('.badge-issueView-notify')
			if(_el.length>0){
				_el.html(cnt);
			}
			
		}
		,
		/**
		 * 显示采购提示信息
		 */
		updateProcurementNotify:function(){
			var _param = {
				url:'/'+init.getSite()+'/procurementDirect/query/getPlanCount.action',								
				async:false,
				success:function(data){					
					if(data){
						
						var typeName=['plan_count','material_small_count','material_mid_count','material_big_count','asset_little_count','asset_small_count','asset_mid_count','asset_big_count','asset_large_count']
						var typeNotify=['procurementPlan','procurementMaterialSmall','procurementMaterialMid','procurementMaterialBig','procurementAssetLittle','procurementAssetSmall','procurementAssetMid','procurementAssetBig','procurementAssetLarge']
						
						
						for(var i =0 ;i<typeName.length;i++){							
							var _num = parseInt(data[typeName[i]]);
							var _notifyEl = $('.badge-'+typeNotify[i] + '-notify');
							if(_notifyEl.length==1){
								if(!_num || _num==0){
									_notifyEl.html('');
								}else{
									_notifyEl.html(_num);
								}
							}							
						}						
					}
				}
				,
				failure:function(){
					bsMsgServ.errorSlide(codeDef.getConfig({type:'load',code:'error'}))
				}
				
			}
			
			$.ajax(_param)
		}
		,
		
		/**
		 * 显示采购提示信息
		 * @param _options.plan_id
		 * @param _options.userid
		 */
		updateProcurementFlowNotify:function(_options){
			var _param = {
				url		:'/'+init.getSite()+'/procurementDirect/query/getFlowCount.action',	
				data	: _options,
				async	:false,
				success	:function(data){					
					if(data){
						
							
						var typeName=[						
							'navFlow','navSchema', 'navBargain','navPublic','navContract'							
						];		
						
						for(var i =0 ;i<typeName.length;i++){							
							var _num = parseInt(data[typeName[i]]);
							var _notifyEl = $('.badge-'+typeName[i] + '-notify');
							if(_notifyEl.length==1){
								if(!_num || _num==0){
									_notifyEl.html('');
								}else{
									_notifyEl.html(_num);
								}
							}							
						}									
					}
				}
				,
				failure:function(){
					bsMsgServ.errorSlide(codeDef.getConfig({type:'load',code:'error'}))
				}
				
			}
			
			$.ajax(_param)
		}
		,
		/**
	     * 加载json的数据到页面的表单中，以name为唯一标示符加载
	     * @param {String} data json表单数据
	     */
	    loadData:function(data){
	        try{
	            //var obj = eval("("+data+")");
	            var obj = data;
	            var key,value,tagName,type,arr;
	            for(var x in obj){
	                key = x;
	                value = obj[x];
	
	                $("[name='"+key+"'],[name='"+key+"[]']").each(function(){
	                    tagName = $(this)[0].tagName;
	                    type = $(this).attr('type');
	                    if(tagName=='INPUT'){
	                        if(type=='radio'){
	                            $(this).attr('checked',$(this).val()==value);
	                        }else if(type=='checkbox'){
	                            arr = value.split(',');
	                            for(var i =0;i<arr.length;i++){
	                                if($(this).val()==arr[i]){
	                                    $(this).attr('checked',true);
	                                    break;
	                                }
	                            }
	                        }else{
	                            $(this).val(value);
	                        }
	                    }else if(tagName=='SELECT' || tagName=='TEXTAREA'){
	                        $(this).val(value);
	                    }
	
	                });
	            }
	        }catch(e){
	            alert("加载表单："+e.message+",数据内容"+JSON.stringify(data));
	        }
	    }
	    
	    ,
	    /**
	     * 求和再相乘
	     * @param _options.rootid
	     * @param _options.sumEl
	     * @param _options.mulEl
	     */
	    sumAndMul:function(_options){
	    	
	    	var _sum = 0;
	    	var _mul = 1;
	    	if(_options && _options.rootid){
	    		var _rootid = _options.rootid;
	    		//获取求和字段值
	    		if(_options.sumEl){
	    			$.each(_options.sumEl,function(i,o){
	    				var _el = $('#'+_rootid + ' #'+o);
	    				_sum += private_method.getNumric(_el);
	    			})
	    		}
	    		//获取求积字段值
	    		if(_options.mulEl){
	    			$.each(_options.mulEl,function(i,o){
	    				var _el = $('#'+_rootid + ' #'+o);
	    				var _tmp = private_method.getNumric(_el);
	    				if( _tmp<=0){
	    					return false;
	    				}else{
	    					_mul *=_tmp;
	    				}
	    			})
	    		}
	    		
	    		if(_sum>0 && _mul>0){
	    			return _sum * _mul;
	    		}else{
	    			return 0;
	    		}
	    		
	    	}
	    	
	    }
	    ,
	    /**
	     * 初始化附件组件
	     * 
	     * @param _options.rootid		dom根节点id
	     * @param _options.containerid	附件容器dom节点id
	     * @param _options.bizcode		业务编码
	     * @param _options.bizno		记录id
	     * @param _options.queueComplete	成功回调函数
	     * @param _options.uploadComplete	成功回调函数
	     * @param _options.error		失败回调函数
	     */
	    initUpload:function(_options){
			
	    	var _ac = $('#'+_options.rootid + ' #'+_options.containerid)
	    	if(_ac.length<=0){
	    		return ;
	    	}
	    	
	    	var _default = {
	    		bizcode		  : null,
	    		bizno		  : null,
	    		rootid		  : null,
	    		queueComplete : null,
	    		uploadComplete: null
	    	}
	    	
	    	$.extend(_default,_options);
	    	_ac.empty();
	    	_ac.append(_archiveUploadHtml);
	    	
			var _data = {bizcode:_default.bizcode,bizno:_default.bizno};;
			
			//初始化上传附件组件
			uploadfiles.init({
				data:_data,							
				queue_id: _default.rootid + ' #queue',
				file_id : _default.rootid + ' #file_upload',
				rootPath: '/'+init.getSite(),
				rootid  : _default.rootid,
				auto    : true,
				removeCompleted : true ,
				queueComplete : function(file,data){
					var _param = {
						file	: file,
						data	: data,
						bizcode : _default.bizcode,
						rootid  : _default.rootid
					}
					if(_default.queueComplete){
						_default.queueComplete(_param)
					}else{
						private_method.upload_success(_param)
					}
				},
				uploadComplete: function(file,data,response){
					var _param = {
						file	: file,
						data	: data, 
						response: response,
						bizcode : _default.bizcode,
						rootid  : _default.rootid,
						del		: true
					}
					if(_default.uploadComplete){
						private_method.uploadComplete(_param);
					}else{
						private_method.uploadSuccess(_param)
					}
				}
				
			});	
			private_method.initArchive(_options);
		}
		,
		/**
		 * 初始化附件预览功能
		 * 
	     * @param _options.rootid			dom根节点id
	     * @param _options.containerid		附件容器dom节点id
	     * @param _options.bizcode			业务编码
	     * @param _options.bizno			业务id
	     * @param _options.queueComplete	成功回调函数
	     * @param _options.uploadComplete	成功回调函数
	     * @param _options.error			失败回调函数
		 */
		initArchive:function(_options){
			
			var _ac = $('#'+_options.rootid + ' #'+_options.containerid)
	    	if(_ac.length==1){
	    		_ac.empty();
	    		_ac.append(_archivePreviewHtml);
	    		private_method.initArchive(_options);
	    	}
			
		}
		
	    ,
		getflowData:function(_options){
			private_method.getflowData(_options);
		}
		
		,
		
		/**
		 * 金额字段输入控制
		 */
		moneyKeyup : function(e){
			
			if(window.console){
				console.log('moneyKeyup running ...')	
			}
    		var _el = $(e.currentTarget);
    		
    		var p1 = /[^\d\.]/g;	// 过滤非数字及小数点 /g :所有范围中过滤
			var p2 = /(\.\d{4})\d*$/g;
			var p4 = /(\.)(\d*)\1/g;
			
			var ctlVal = _el.val().replace(p1, "").replace(p2, "$1").replace(p4,"$1$2");
			
			
			
			ctlVal=ctlVal.replace(/[^0-9.]/g, '');
			
			// fix bug: many char'.'
			var p5 = /\.+/g;	//多个点的话只取1个点，屏蔽1....234的情况
			ctlVal = ctlVal.replace(p5, ".")
			
			var p6 = /(\.+)(\d+)(\.+)/g; //屏蔽1....234.的情况
			ctlVal = ctlVal.replace(p6, "$1$2")// 屏蔽最后一位的.
			
			_el.val(ctlVal);
    	}
			
	}
	
	var btnEvent = {
		
		downloadFile:function(e){
			var _btn = $(e.currentTarget)
			
			var _id = _btn.attr('aid')
			
			var _url = '/'+init.getSite() +'/upload/downloadFileTest.action'
			var form = $("<form>");
			form.attr('style','display:none');
			form.attr('target','');
			form.attr('method','post');
			form.attr('action',_url);
			var input1 = $("<input>");
			input1.attr('type','hidden')
			input1.attr('name','id')
			input1.attr('value',_id);
			$('body').append(form);
			$(form).append(input1);
			
			form.submit();
			form.remove();
		}
				
		,
		/**
		 * @param _options.evt	按钮事件
		 * @param _options.bizcode	业务编码
		 * @param _options.rootid	dom根节点id
		 * @param _options.bizno	业务记录id
		 */
		removeFile:function(_options){
			var _default = {
				evt		: null,
				bizcode : null,
				rootid	: null
			}
			
			$.extend(_default,_options);
			
			if(_default.evt && _default.evt.currentTarget){
				
				var _btn = $(_default.evt.currentTarget);				
				var _id = _btn.attr('aid')				
				if(_id){
					$.messager.confirm('警告', '确定执行删除操作?', function(r){
					
						if( r){	
							var _url = '/'+init.getSite() +'/upload/del.action';
							$.ajax({
								url:_url,
								data:{id:_id},
								success:function(data){
									if(data && data.status=='success'){
										private_method.initArchive({
											bizcode	: _options.bizcode,
											rootid	: _options.rootid,
											del		: true,
											bizno	: _options.bizno
										});
										bsMsgServ.msgSlide();
									}else{
										bsMsgServ.warnSlide();
									}
								}
								,
								error:function(){
									bsMsgServ.warnSlide();
								}
							})
						}
					})
				}
			}
			
		}
		,
		previewFile:function(e){
			var _btn = $(e.currentTarget)
			
			var _id = _btn.attr('aid')
			if(_id){
				var _url = '/portal/preview.action?id='+_id;
				
				window.open(_url);
			}
		}
		
	}
	
	var private_method = {
		
		/**
		 * 获取通知公告类型值
		 */
		getNotifyid:function(){
			return {typeid:16}
		}
		,
		/**
		 * 获取字段数值，非数值返回0
		 */
		getNumric:function(el){
			var ret = 0
			if(el && el.length==1){
				var _tmp = el.val();
				if(_tmp &&　$.isNumeric(_tmp)){
					ret =parseFloat(_tmp);
				}
			}
			return ret;
		}		
		,
		/**
		 * 上传成功提示函数
		 * @param _options.rootid	dom根节点
		 * @param _options.file		控件参数
		 * @param _options.data		控件参数
		 * @param _options.bizcode	业务编码
		 */
		upload_success:function(_options){
			if(window.console && _options)
				console.log(_options.data);				
			
			var _data = {
					bizcode: _options.bizcode,
					rootid : _options.rootid,
					del	   : true
				}
			
			var _id =$('#'+_options.rootid + ' #id').val()
			if(_id){
					_data.bizno=_id	}
			
			private_method.initArchive(_data);
			bsMsgServ.msgSlide('文件上传成功')
		},
		
		/**
		 * @param _options.file		控件参数
		 * @param _options.data		控件参数
		 * @param _options.response	控件参数
		 * @param _options.bizcode	业务编码
		 * @param _options.rootid	根节点id
		 */
		uploadSuccess:function(_options){					
			
			var _data = {
				bizcode: _options.bizcode,
				rootid : _options.rootid,
				del	   : true
			}
			
			var _id =$('#'+_options.rootid + ' #id').val()
			if(_id){
				_data.bizno=_id	;				
			}
			
			private_method.initArchive(_data);
			bsMsgServ.msgSlide('文件上传成功')
		},
		
		/**
		 * 初始化附件信息
		 * @param _options.bizcode	业务编码
		 * @param _options.rootid	dom跟节点
		 * @param _options.del		允许删除
		 */
		initArchive:function(_options){
			
			var _default = {
				bizcode : null,
				bizno   : null,
				rootid  : null,
				del     : false,
				isAudit : false	//是否启用审核
			}
			//参数获取
			$.extend(_default,_options);
			
			//定位附件
			var _el = $('#' + _default.rootid + ' #archive');
			
			if(_el.length>0){
				_el.empty();
				/**
				 * 根据审核状态判断是否显示按钮栏
				 */
				var showToolBar = true
				
				if(_default.isAudit){
					if(buttonEvent.checkAuditStatus({editWindow:rootid})){
						showToolBar = false
					}	
				}			
				
				var _data = {bizcode:_default.bizcode,bizno:_default.bizno};
				
				var _param = {
					url:'/'+init.getSite()+uploadListurl,
					data:{condition:_data},
					type: 'post',
					success:function(data){
						if(window.console){
							console.log(' archive init ...')
						}
						var _html ='';
						if(data && data.rows){
							_html = '<ul>'
							$.each(data.rows,function(i,o){
								if(o.filename){
									_html += '<li><span>'+o.filename+'</span>'
									         
									var _name = o.filename.split('.');
									if(_name.length>0){
										var _extname = _name[_name.length-1];
										var _type = '';
										switch(_extname){
											case 'doc':
												_type = _extname;
												break;
											case 'docx':
												_type = _extname;
												break;
//												case 'xls':
//													_type = _extname;
//													break;
//												case 'xlsx':
//													_type = _extname;
//													break;
											default:
												
										}
									}
									
									if(_type){
										_html += '<a class="archive-preview archive-btn" btn-type="preview" aid="'+o.id+'" >'+'        预览' +'</span></a>';
										
									}
									
									_html += '<a class="archive-info archive-btn" btn-type="download" aid="'+o.id+'">'+'        下载'+'</a>' 
									
									if(_options && _options.del){
										_html += '<a class="archive-remove archive-btn" btn-type="remove" aid="'+o.id+'"><span style="color:red">'+'        删除' +'</span></a>' 
									}
									
									_html +='</li>';	
								}
							})
							
							_html +='</ul>'
						}
						
						
						_el.append(_html);
						
						//绑定下载点击事件
						var file_btn = $('#'+_default.rootid + ' .archive-info')
						if(file_btn.length>0){
							file_btn.unbind('click')
							file_btn.bind('click',	btnEvent.downloadFile)
						}
						
						//绑定预览点击事件
						var file_btn = $('#'+_default.rootid + ' .archive-preview')
						if(file_btn.length>0){
							file_btn.unbind('click')
							file_btn.bind('click',	btnEvent.previewFile)
						}
						
						//绑定下载点击事件
						var file_btn = $('#'+_default.rootid + ' .archive-remove')
						if(file_btn.length>0){
							file_btn.unbind('click')
							file_btn.bind('click',	
								function(e){
									btnEvent.removeFile({
										rootid	: _default.rootid,
										bizcode : _default.bizcode,
										bizno	: _default.bizno,
										evt		: e
									})
								}
							)
						}
						
					}
				}
				
				$.ajax(_param);
			}
		}
		,
		/**
		 * 获取流程业务数据
		 * @param _options.bizcode
		 * @param _options.flowInstId
		 * @param _options.callback
		 */
		getflowData:function(_options){
			if(_options && _options.flowInstId && _options.bizcode){
				
				
				//业务记录存在，查询业务记录数据
				var _urlBase = '/' + init.getSite() +'/' + _options.bizcode;						
				//获取流程记录						
				var bizRowUrl = _urlBase +'/query/getOneByBizTable.action';
				
				$.ajax({
					url:bizRowUrl,
					type:'post',
					contentType:'application/x-www-form-urlencoded; charset=UTF-8',
					data:{field:'flowInstId',fieldVal:_options.flowInstId},
					success:function(data){
						if(_options.callback){
							_options.callback(data);	
						}
					},
					error:function(){
						
					}
				})
			}
		}
		
	}
	
	return public_method;
})